#!/usr/bin/env python3
# -*- encoding: utf-8 -*-

import json
import logging

class PollStock:
    def __init__(self, name, items, interval) -> None:
        self.name = name
        self.items = items
        self.interval = interval

class PollFund:
    def __init__(self, name, items, interval) -> None:
        self.name = name
        self.items = items
        self.interval = interval

class Poll:
    def __init__(self) -> None:
        self.stocks = []
        self.funds = []

class Config(object):
    def __init__(self) -> None:
        self.database = "finance"
        self.user = "postgres"
        self.password = "123456"
        self.host = "127.0.0.1"
        self.port = "5432"
        self.recoderLimit = 300  # 1年
        self.poll_data:Poll = Poll()

    def LoadConfig(self, config_dir:str) -> bool:
        self.OpenJson(config_dir+"/config.json")
        self.OpenPollingTarget(config_dir+"/poll.json")

    def OpenJson(self, filename: str)->None:
        with open(filename, mode='r') as file:
            data = json.load(file)
            db_param = data["db"]
            self.database = db_param["database"]
            self.user = db_param['user']
            self.password = db_param['password']
            self.host = db_param['host']
            self.port = db_param['port']
            del(data)

    def OpenPollingTarget(self, filename: str) -> None:
        try:
            with open(filename, mode='r') as file:
                data = json.load(file)
                stocks_json = data["stocks"]
                for stock in stocks_json:
                    self.poll_data.stocks.append(PollStock(stock["name"], stock["items"], stock["interval"]))
                fund_json = data["funds"]
                for fund in fund_json:
                    self.poll_data.funds.append(PollStock(stock["name"], stock["items"], stock["interval"]))
                logging.debug(self.poll_data)
        except Exception as e :
            logging.fatal("open file: {} errmsg={}".format(filename, e))


g_config = Config()